import React, { useState,useEffect } from "react";
import Constants from "expo-constants";
import {
  Button,
  Text,
  TextInput,
  View,
  ScrollView,
  Pressable,
  StyleSheet,
  Image,
  FlatList,
} from "react-native";
import { Picker } from "@react-native-picker/picker";
import Icon from "react-native-vector-icons/FontAwesome";
import Ionicons from "react-native-vector-icons/Ionicons";
import Icon1 from "react-native-vector-icons/FontAwesome5";
import { useNavigation } from "@react-navigation/native";
import * as ImagePicker from "expo-image-picker";
import * as FileSystem from "expo-file-system";
import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";
const myImage = require("../assets/guide.png");
const leftbutton = require("../assets/leftbutton.png");
const rightbutton = require("../assets/rightbutton.png");
const ActivityTypes = [
  "自习",
  "电影",
  "聚餐",
  "拼车",
  "拼单",
  "游戏",
  "运动",
  "旅行",
  "其他",
];
const color = [
  "#4094F7",
  "#FE6386",
  "#F6A514",
  "#FD7C42",
  "#FE655F",
  "#00B773",
  "#B758FD",
  "#03BBD1",
  "#4CA4FD",
];

const ActivityPost = () => {
  const navigation = useNavigation();
  const [selectedActivity, setSelectedActivity] = useState(ActivityTypes[0]);
  const [postText, setPostText] = useState("");
  const [peopleCount, setpeopleCount] = useState("");
  const [image, setImage] = useState(null);
  const [time, setTime] = useState("");
  const [userInfo, setUserInfo] = useState({});
  const [dy_id, setDy_id] = useState("");
  const [refreshing, isRefresh] = useState(true);
  const getFormattedCurrentTime = () => {
    const now = new Date(); // 获取当前时间
    const year = now.getFullYear(); // 年
    const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 月，月份是从0开始计数的
    const day = now.getDate().toString().padStart(2, "0"); // 日
    const hours = now.getHours().toString().padStart(2, "0"); // 时
    const minutes = now.getMinutes().toString().padStart(2, "0"); // 分
    const seconds = now.getSeconds().toString().padStart(2, "0"); // 秒

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  useEffect(() => {
    (async () => {
      const userinfo = await AsyncStorage.getItem("userInfo");
      if (userinfo) {
        setUserInfo(JSON.parse(userinfo));
      }
      await axios
        .get("http://47.111.227.58:3000/dynamic/getactivity")
        .then((res) => {
        //   setDy_id(res.data.results[0].id);
        });
      const currentTime = getFormattedCurrentTime();
      setTime(currentTime);
      console.log(time);
      // 请求权限
      const { status } =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== "granted") {
        console.log("拒绝访问图片库权限！");
      }
    })();
  }, []);
  const handlePost = async () => {
    const currentTime = getFormattedCurrentTime();
    setTime(currentTime);
    console.log(time);
    axios
      .post("http://47.111.227.58:3000/dynamic/addActivity", {
        data: {
          username: userInfo.username,
          phone: userInfo.phone,
          desc: postText,
          userImg: userInfo.imgUrl,
          uploadTime: time,
          imgUrl: image,
          board: selectedActivity,
          peopleNum: peopleCount,
        //   boardColor: color[ActivityTypes.indexOf(selectedActivity)],
        },
      })
      .then((response) => {
        console.log(userInfo.characters);
        axios
          .post("http://47.111.227.58:3000/dynamic/updataIdCharacter", {
            data: {
              character: Number(userInfo.characters) + 1,
              id: userInfo.id,
            },
          })
          .then((res) => {
            console.log(res.data);
            userInfo.characters = Number(userInfo.characters) + 1;
            AsyncStorage.setItem("userInfo", JSON.stringify(userInfo));
          });
      })
      .catch((error) => {
        console.error(error);
      });
    console.log("发布的板块: ", selectedActivity);
    console.log("发布的正文: ", postText);
    setPostText("");
    setImage(null);
  };
  const convertImageToBase64 = async (imageUri) => {
    try {
        const base64Data = await FileSystem.readAsStringAsync(imageUri, {
            encoding: FileSystem.EncodingType.Base64,
        });
        return base64Data;
    } catch (error) {
        console.error(error);
    }
}
  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 4],
      quality: 1,
    });

    console.log(result.assets[0]);

    // 检查图片是否是Base64格式
    if (!/^data:image\/[a-zA-Z]*;base64,/.test(result.assets[0].uri)) {
      convertImageToBase64(result.assets[0].uri)
        .then((base64Data) => {
          console.log("Image (base64): ", base64Data);
          setImage("data:image/jpg;base64," + base64Data);
        })
        .catch((err) => {
          console.error("Error converting image to base64", err);
        });
    } else {
      setImage(result.assets[0].uri);
    }
  };
  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: false,
      quality: 1, // 视频选择不支持编辑，此选项可以设置视频的质量
    });
    if (!result.canceled) {
      const video = result.assets[0];
      console.log(video);
      // 视频的本地 URI 在 video.uri
    }
  };
  const deleteButton = () => {
    setImage(null);
  };
  const tagsData = ActivityTypes.map((type, index) => ({
    type: type,
    iconColorKey: `TagColor${(index % 9) + 1}`,
    color: color[index],
  }));
  const handleTagPress = (type) => {
    if (selectedActivity === type) {
      setSelectedActivity("");
    } else {
      setSelectedActivity(type);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>活动主题</Text>
      </View>
      <View style={styles.Tags}>
        {tagsData.map((tagData) => (
          <Pressable
            key={tagData.type} // 使用 Tag 类型作为 key
            style={[
              styles.Tag,
              {
                backgroundColor:
                  selectedActivity === tagData.type ? tagData.color : "#FFFDF1",
              }, // 根据选中状态改变背景颜色
            ]}
            onPress={() => handleTagPress(tagData.type)}
          >
            <View style={[styles[tagData.iconColorKey]]}></View>
            <Text style={styles.TagContent}>{tagData.type}</Text>
          </Pressable>
        ))}
      </View>
      <View style={styles.header}>
        <Text style={styles.headerText}>活动详情</Text>
      </View>
      <View style={styles.content}>
        <View style={styles.contentTop}>
          <TextInput
            style={styles.input}
            multiline={true}
            placeholder="在此处输入正文..."
            placeholderTextColor="#BABABA"
            onChangeText={(text) => setPostText(text)}
            value={postText}
          />
        </View>
        <View style={styles.contentBottom}>
          <Pressable onPress={pickImage}>
            {!image ? (
              <View style={styles.contentBottomimage}>
                <Icon
                  name="photo"
                  style={styles.contentBottomIcon}
                  size={20}
                  color="#969696"
                />
                <Text style={styles.contentBottomText}>添加图片</Text>
              </View>
            ) : null}
            {image && (
              <>
                <Image
                  source={{ uri: image }}
                  style={{ width: 70, height: 70, marginLeft: 10 }}
                />
                <Pressable
                  onPress={deleteButton}
                  style={styles.deleteButton}
                >
                  <Icon name="window-close" size={15} color="#ff0000" />
                </Pressable>
              </>
            )}
          </Pressable>
        </View>
      </View>
      <View style={styles.header}>
        <Text style={styles.headerText}>总人数</Text>
      </View>
      <View style={styles.BottomContent}>
        <View style={styles.BottomContentLeft}>
          <Text style={styles.headerText}>总人数</Text>
          <Ionicons name="male-female" size={16} color="#EC807C"></Ionicons>
        </View>
        <View style={styles.BottomContentRight}>
          <TextInput
            style={styles.BottomContentInput}
            multiline={true}
            placeholder="请输入总人数"
            placeholderTextColor="#BABABA"
            onChangeText={(text) => setpeopleCount(text)}
            value={peopleCount}
          />
        </View>
      </View>
      <Pressable onPress={handlePost} style={styles.BottomButton}>
        <Text style={styles.BottomButtonText}>发布</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  deleteButton: {
    position: "absolute",
    top: -5,
    right: -5,
  },
  container: {
    backgroundColor: "#FAD874",
    width: "100%",
    height: "100%",
    paddingTop: Constants.statusBarHeight,
  },
  header: {
    flexDirection: "row",
    padding: 5,
    paddingLeft: 10,
  },
  headerText: {
    fontSize: 16,
    color: "#000",
    fontWeight: "bold",
    marginLeft: 10,
  },
  Tags: {
    width: "100%",
    height: "15%",
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap",
    // overflow: 'visible'
    // marginTop: -20,
  },
  TopTags: {
    flexDirection: "row",
    width: "100%",
    height: "50%",
  },
  BottomTags: {
    flexDirection: "row",
    width: "100%",
    height: "50%",
    marginTop: -10,
  },
  Tag: {
    flexDirection: "row",
    width: "18%",
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    borderRadius: 5,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    margin: 10,
    marginLeft: 6,
    marginRight: 0,
    display: "flex",
    alignItems: "center",
    // padding: 5,
  },
  TagColor1: {
    width: "10%",
    height: "100%",
    backgroundColor: "#4094F7",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor2: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FE6386",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor3: {
    width: "10%",
    height: "100%",
    backgroundColor: "#F6A514",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor4: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FD7C42",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor5: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FE655F",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor6: {
    width: "10%",
    height: "100%",
    backgroundColor: "#00B773",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor7: {
    width: "10%",
    height: "100%",
    backgroundColor: "#B758FD",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor8: {
    width: "10%",
    height: "100%",
    backgroundColor: "#03BBD1",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor9: {
    width: "10%",
    height: "100%",
    backgroundColor: "#4CA4FD",
    display: "flex",
    alignItems: "flex-start",
  },
  TagIcon: {
    color: "#9B999C",
    display: "flex",
  },
  TagTitle: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#9B999C",
    display: "flex",
  },
  TagContent: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#24201D",
    display: "flex",
    marginLeft: 12,
  },
  content: {
    height: 250,
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    borderRadius: 5,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    marginLeft: 10,
    marginRight: 10,
  },
  contentTop: {
    height: 175,
    flexDirection: "row",
  },
  contentBottom: {
    height: 75,
    backgroundColor: "#FFFDF1",
    flexDirection: "row",
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
  },
  contentBottomimage: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomvideo: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomIcon: {
    position: "absolute",
    top: "25%",
    left: "34%",
  },
  contentBottomText: {
    position: "absolute",
    top: "55%",
    left: "21%",
    color: "#BABABA",
    fontSize: 10,
  },
  input: {
    height: 175,
    width: "100%",
    padding: 10,
  },
  contentTopRight: {
    height: 175,
    width: "20%",
    flexDirection: "column",
  },
  contentTopRightIcon: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F4F4F4",
    margin: 25,
    marginLeft: 30,
    marginRight: 10,
  },
  contentTopRightIconItem: {
    margin: 5,
  },
  BottomContent: {
    display: "flex",
    flexDirection: "row",
    // width: '90%',
    height: "10%",
    justifyContent: "space-between",
    alignItems: "center",
    borderRadius: 5,
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    marginLeft: 10,
    marginRight: 10,
  },
  BottomContentLeft: {
    display: "flex",
    flexDirection: "row",
  },
  BottomContentRight: {
    display: "flex",
    width: "20%",
    marginRight: 10,
  },
  BottomContentInput: {
    display: "flex",
    width: "100%",
  },
  BottomButton: {
    backgroundColor: "#FD6A61",
    color: "#fff",
    padding: 10,
    marginRight: 15,
    marginLeft: 15,
    borderRadius: 20,
    marginTop: 10,
    alignItems: "center",
    justifyContent: "center",
  },
  BottomButtonText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 14,
  },
});

export default ActivityPost;
